/*
 *  Circle.cpp
 *  BugFix
 *
 *  Created by Dmitry Fadeev on 9/14/11.
 *  Copyright 2011 Arello Mobile. All rights reserved.
 *
 */

#include <physics/Circle.h>
#include <box2d/dynamics/b2Fixture.h>
#include <box2d/collision/shapes/b2CircleShape.h>

namespace physics
{
	
Circle::Circle(World *world)
	: Node(world)
{
}
	
Circle::Circle(World *world, float radius, const Vector2 & center)
	: Node(world)
	, radius(radius)
{
	CreateDefaultBody();

	b2FixtureDef fd;
	fd.density = 1.0f;
	fd.friction = 0.0f;
	fd.restitution = 0.0f;

	b2CircleShape shape;
	shape.m_p.Set(center.x / GetWorldPixelsInMeter(), center.y / GetWorldPixelsInMeter());
	shape.m_radius = radius / GetWorldPixelsInMeter();

	fd.shape = &shape;

	body->CreateFixture(&fd);
}

std::auto_ptr <xml::ObjectANSI> Circle::CreateLoader()
{
	return std::auto_ptr <xml::ObjectANSI> (new CircleLoader(this));
}

Vector2 Circle::GetSize() const
{
	return Vector2(radius * 2.0f, radius * 2.0f);
}

// ------------------------------------------------------------------------------------
// ------------------------------------ Loader ----------------------------------------
// ------------------------------------------------------------------------------------

bool CircleLoader::on_attribute(xml::Provider *prov, const std::string &name, const std::string &value)
{
	if(name == "Radius")
	{
		if(!converter::convert(value, &radius))
			return false;
		
		static_cast<Circle*>(node)->radius = radius;
		
		return true;
	}
	if(name == "Center")
	{
		if(!converter::convert(value, &center))
			return false;
			
		return true;
	}
		
	return NodeLoader::on_attribute(prov, name, value);
}
	
std::auto_ptr <b2Shape> CircleLoader::CreateShape()
{
	std::auto_ptr <b2CircleShape> circle(new b2CircleShape());
	circle->m_p.Set(center.x / node->GetWorldPixelsInMeter(), center.y / node->GetWorldPixelsInMeter());
	circle->m_radius = radius / node->GetWorldPixelsInMeter();
		
	return std::auto_ptr <b2Shape>(circle.release());
}
	
}	// namespace physics